package com.sywb.chuangyebao.view.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.contract.PublishVideoFromCameraContract;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.PublishVideoActivity;
import com.sywb.chuangyebao.view.PublishVideoEditActivity;
import com.sywb.chuangyebao.view.dialog.AlertDialog;
import com.sywb.chuangyebao.widget.RECProgressView;
import com.tencent.rtmp.ui.TXCloudVideoView;

import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;

import java.io.File;

/**
 * 通过拍摄发布视频
 */
public class PublishVideoFromCameraFragment extends BaseStatisticsFragment<PublishVideoFromCameraContract.Presenter> implements PublishVideoFromCameraContract.View, View.OnTouchListener {

    public static final String TAG = "PublishVideoFromCameraFragment";

    private TXCloudVideoView mTXCloudVideoView;
    private RECProgressView mRECProgressView;
    private ImageView mIvRecing;
    private TextView mTvTime;
    private ImageView mIvClose;
    private ImageView mIvSwitchCamera;
    private TextView mTvDel;
    private TextView mTvNext;
    private ImageView mIvStartRecord;

    private boolean isStartRecord = true;
    private boolean mFront = false;
    private String mOutputPath; // 合并的视频文件

    /**
     * Fragment 实例
     */
    public static PublishVideoFromCameraFragment newInstance(Object... pramars) {
        PublishVideoFromCameraFragment fragment = new PublishVideoFromCameraFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_publish_video_from_camera;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);

        mTXCloudVideoView = getView(R.id.surfaceView_fragment_publish_video_from_camera);

        mIvSwitchCamera = getView(R.id.ivSwitchCamera_fragment_publish_video_from_camera);
        mIvSwitchCamera.setOnClickListener(this);

        mIvClose = getView(R.id.ivClose_fragment_publish_video_from_camera);
        mIvClose.setOnClickListener(this);

        mIvStartRecord = getView(R.id.ivStartRecord_fragment_publish_video_from_camera);
        mIvStartRecord.setOnTouchListener(this);
        recordEnabled(false);

        mRECProgressView = getView(R.id.recProgress_fragment_publish_video_from_camera);

        mIvRecing = getView(R.id.ivRecing_fragment_publish_video_from_camera);
        Glide.with(getActivity()).asGif().load(R.drawable.video_recording).into(mIvRecing);
        mIvRecing.setVisibility(View.GONE);

        mTvTime = getView(R.id.tvTime_fragment_publish_video_from_camera);
        mTvTime.setVisibility(View.GONE);

        mTvDel = getView(R.id.tvDel_fragment_publish_video_from_camera);
        mTvDel.setOnClickListener(this);
        mTvDel.setVisibility(View.GONE);

        mTvNext = getView(R.id.tvNext_fragment_publish_video_from_camera);
        mTvNext.setOnClickListener(this);
        mTvNext.setVisibility(View.GONE);
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (!isCanClick(v)) return;
        switch (v.getId()) {
            case R.id.ivSwitchCamera_fragment_publish_video_from_camera:
                mFront = mPresenter.switchCamera(mFront);
                break;
            case R.id.ivClose_fragment_publish_video_from_camera:
                exit();
                break;
            case R.id.tvDel_fragment_publish_video_from_camera:
                showDelDialog();
                break;
            case R.id.tvNext_fragment_publish_video_from_camera:
                showProgress();
                mPresenter.stopRecording();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (((PublishVideoActivity) getActivity()).getTabPosition() == 1) {
            mPresenter.startPreview();
            getSurfaceView().setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(mOutputPath)) {
                // 删除合并的视频文件（进入编辑页面会从新合并）
                Utils.delFile(new File(mOutputPath));
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.stopPreview();
        getSurfaceView().setVisibility(View.GONE);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(TAG)})
    public void onVisibleChange(String visible) {
        if ("onPause".equals(visible)) {
            onPause();
        } else if ("onResume".equals(visible)) {
            onResume();
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_VIDEO_SAVE)})
    public void onPublishSuccess(String data) { // 视频发布成功
        mPresenter.deleteAllPart();
        if (!TextUtils.isEmpty(mOutputPath)) {
            // 删除合并的视频文件
            Utils.delFile(new File(mOutputPath));
        }

        if (((PublishVideoActivity) getActivity()).getTabPosition() == 1) { // 判断Tab是在当前页面，避免两个tab都执行exit
            exit();
        }

    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    @Override
    public TXCloudVideoView getSurfaceView() {
        return mTXCloudVideoView;
    }

    @Override
    public int getMaxDuration() {
        return mRECProgressView.getMaxProgress();
    }

    @Override
    public int getMinDuration() {
        return mRECProgressView.getMinProgress();
    }

    @Override
    public void onDrawReady() {
        recordEnabled(true);
    }

    @Override
    public void onFinishedRecord(String outputPath) {
        hideProgress();
        if (mRECProgressView.getProgress() == mRECProgressView.getMaxProgress()) {
            showMessage(getString(R.string.rec_maxed));
        }
        mOutputPath = outputPath;
        advance(PublishVideoEditActivity.class, outputPath, 1, mRECProgressView.getProgress() / 1000);
    }

    @Override
    public void onProgressChanged(long duration, boolean isComplete) {
        long totalDuration = duration;
//        if (!mRECProgressView.getPoints().isEmpty()) {
//            totalDuration += mRECProgressView.getPoints().get(mRECProgressView.getPoints().size() - 1).intValue();
//        }

        if (totalDuration > mRECProgressView.getMaxProgress()) {
            totalDuration = mRECProgressView.getMaxProgress();
        }

        mRECProgressView.setProgress((int) totalDuration);
        mTvTime.setText(DateTimeUtils.getRECTime(totalDuration));

        if (totalDuration >= mRECProgressView.getMaxProgress()) {
            mTvDel.setVisibility(View.VISIBLE);
            mTvNext.setVisibility(View.VISIBLE);

            recordEnabled(false);
            mPresenter.pauseRecording();
            mRECProgressView.addPoint(mRECProgressView.getProgress());
            mTvTime.setVisibility(View.GONE);
            mIvRecing.setVisibility(View.GONE);
            mIvSwitchCamera.setVisibility(View.VISIBLE);
            mIvClose.setVisibility(View.VISIBLE);
        } else {
            mTvDel.setVisibility(View.VISIBLE);
            recordEnabled(true);
            if (totalDuration >= mRECProgressView.getMinProgress()) {
                // 总的录制时间大于最小录制时间时，下一步按钮才可用
                mTvNext.setVisibility(View.VISIBLE);
            }
        }

//
//        if (isComplete) {
//            mRECProgressView.addPoint(mRECProgressView.getProgress());
//            mTvDel.setVisibility(View.VISIBLE);
//            recordEnabled(true);
//
//            if (totalDuration >= mRECProgressView.getMinProgress()) {
//                // 总的录制时间大于最小录制时间时，下一步按钮才可用
//                mTvNext.setVisibility(View.VISIBLE);
//            }
//
//        }
    }

    @Override
    public void onMaxDuration() {
        showProgress();
        mPresenter.stopRecording();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) { // 按下开始录制
            if (!mPresenter.isRecording()) {
                if (mRECProgressView.getProgress() < mRECProgressView.getMaxProgress()) {
                    mTvTime.setVisibility(View.VISIBLE);
                    mIvRecing.setVisibility(View.VISIBLE);
                    mIvSwitchCamera.setVisibility(View.GONE);
                    mIvClose.setVisibility(View.GONE);
                    mTvNext.setVisibility(View.GONE);
                    mTvDel.setVisibility(View.GONE);

                    if (isStartRecord) {
                        isStartRecord = false;
                        mPresenter.startRecording();
                    } else {
                        mPresenter.resumeRecording();
                    }
//                    if (mRECProgressView.getProgress() > 0) {
//                        mRECProgressView.addPoint(mRECProgressView.getProgress());
//                    }
                } else {
                    showMessage(getString(R.string.rec_maxed));
                    return true;
                }
            }

        } else if (event.getAction() == MotionEvent.ACTION_UP) { // 松开停止录制
            if (mPresenter.isRecording()) {
                recordEnabled(false);
                mPresenter.pauseRecording();
                mRECProgressView.addPoint(mRECProgressView.getProgress());
                mTvTime.setVisibility(View.GONE);
                mIvRecing.setVisibility(View.GONE);
                mIvSwitchCamera.setVisibility(View.VISIBLE);
                mIvClose.setVisibility(View.VISIBLE);
            }
        }
        return false;
    }

    private void recordEnabled(boolean enabled) {
        mIvStartRecord.setClickable(enabled);
        mIvStartRecord.setEnabled(enabled);
        if (enabled) {
            mIvStartRecord.getDrawable().setAlpha(255);
            mIvStartRecord.setOnTouchListener(this);
        } else {
            mIvStartRecord.getDrawable().setAlpha(100);
            mIvStartRecord.setOnTouchListener(null);
        }
    }

    /**
     * 删除上一段视频
     */
    private void showDelDialog() {
        String msg = mActivity.getString(R.string.del_video_part);
        AlertDialog alertDialog = AlertDialog.newInstance(null, msg, null, null, false);
        alertDialog.setClickListener(new AlertDialog.OnClickListener() {
            @Override
            public void onClick(int position) {
                if (position == 1) {
                    mPresenter.deletePart();
                    mRECProgressView.deletePoint();

                    if (mRECProgressView.getPoints().isEmpty()) {
                        // 删完了片段后，需要隐藏删除按钮
                        mTvDel.setVisibility(View.GONE);
                    }

                    if (mRECProgressView.getProgress() < mRECProgressView.getMinProgress()) {
                        // 小于最小录制时间需要隐藏下一步按钮
                        mTvNext.setVisibility(View.GONE);
                    }

                    int second = mRECProgressView.getProgress() / 1000;
                    mTvTime.setText(DateTimeUtils.getRECTime(second));
                }
            }
        });
        alertDialog.show(getMyFragmentManager(), "showDelDialog");
    }
}
